//
//  TKIMToolBar.m
//  TKIM
//
//  Created by liupm on 15/7/27.
//  Copyright (c) 2015年 liupm. All rights reserved.
//

#import "TKIMToolBar.h"
#import "TKIMTextBinding.h"
//#import "TKIMStringHelper.h"


typedef enum
{
    Emotion,
    System,
    Voice,
    More
} IMKeyboardType;



@implementation TKIMToolBarTextView

//-(void)paste:(id)sender
//{
//    NSString *pastStr = [UIPasteboard generalPasteboard].string;
//    if (![TKIMStringHelper isEmpty:pastStr]) {
//        UIFont *font = [UIFont systemFontOfSize:15.0f];
//        CGFloat attchWH = font.lineHeight;
//        CGRect bounds = CGRectMake(0, -4, attchWH, attchWH);
//        self.attributedText =  [TKIMHelper filterTxtMessage:pastStr font:15.0f imageBounds:bounds isDetectLinks:NO];
//        if (self.delegate && [self.delegate respondsToSelector:@selector(textViewDidChange:)]) {
//            [self.delegate textViewDidChange:self];
//        }
//    }
//}

@end

@interface TKIMToolBar()<UITextViewDelegate>

@property(nonatomic,strong) UIButton *reCall;//针对东北证券输入框
@property(nonatomic,strong) UIButton *send;//发送按钮
@property(nonatomic,strong) UIButton *expression;//表情按钮
@property(nonatomic,strong) UIButton *tool;//工具按钮
@property(nonatomic,strong) UIButton *record;//录音按钮


@property(nonatomic,strong) TKIMEmotionView *emotionView;//表情视图
@property(nonatomic,strong) TKIMToolView *toolView;//表情视图
@property(nonatomic,strong) TKIMRecordView *recordView;//录音视图

@property(nonatomic,strong) UIView *activeBottomView;//当前活跃的底部视图
@property(nonatomic,strong) UIButton *activeButton;//当前活跃的底部按钮


@property(nonatomic,strong) UIView *tooBar;//聊天工具栏
@property(nonatomic,strong) UIView *inputBar;//针对东北证券的键盘
@property(nonatomic,strong) UIButton *switchBar;//工具栏切换按钮
@property(nonatomic,strong) TKIMMenuBar *menuBar;//菜单工具栏


@end

static CGFloat keyBoardDuration = 0.25;

@implementation TKIMToolBar
{
    IMKeyboardType _keyBoardType;
    CGFloat ToolBarHeight;
    CGFloat lineWidth;
}

-(instancetype)initWithFrame:(CGRect)frame toolBarType:(TKIMToolBarType)type
{
    self = [super initWithFrame:frame];
    if (self)
    {
        ToolBarHeight = frame.size.height;
        _tooBarType = type;
        _keyBoardType = System;
        [self drawView];
        [self addNotification];
        _isNeedPhoto = YES;
        _isNeedQuick = YES;
    }
    return self;
}



/**
 *  @Author lpm, 15-07-27 14:07:02
 *
 *  @brief  绘制工具栏
 */
-(void)drawView
{
    CGFloat scale = [[UIScreen mainScreen] scale];
    lineWidth = scale > 0.0 ? 1.0 / scale : 1.0;
    self.layer.borderWidth = lineWidth;
    self.layer.borderColor = [TKIMColorHelper stringToColor:@"#cccccc"].CGColor;
    self.backgroundColor = [TKIMColorHelper stringToColor:@"#EFEFF4"];
    if(_tooBarType == TKIMToolBarNormalType)
    {
        [self addSubview:self.tooBar];
    }else if (_tooBarType == TKIMToolBarLonelyType){
    
          [self addSubview:self.reCall];
    }
    else
    {
        [self addSubview:self.menuBar];
    }
    
}


-(void)setTooBarType:(TKIMToolBarType)tooBarType
{
    _tooBarType = tooBarType;
    [self switchToolBar];
    [self setNeedsLayout];
}


-(void)layoutSubviews
{
    [super layoutSubviews];
    if(_tooBarType == TKIMToolBarNormalType)
    {
        self.switchBar.frame = CGRectMake(0, 0, 0, 0);
    }
    else
    {
        self.switchBar.frame = CGRectMake(0, 0, 50, ToolBarHeight);
    }
    
    
    
    CGFloat x =self.switchBar.right==0?3:self.switchBar.right;
    self.record.frame = CGRectMake(x, 4, ToolBarHeight-8,ToolBarHeight-8);
    self.input.frame = CGRectMake(self.record.frame.size.width+self.record.frame.origin.x+2,  self.record.top+4, (self.frame.size.width-3*ToolBarHeight +14-self.switchBar.width), ToolBarHeight*0.7);
    self.expression.frame = CGRectMake(self.input.frame.size.width+self.input.frame.origin.x+2, self.record.frame.origin.y, self.record.frame.size.width,self.record.frame.size.width);
    self.tool.frame = CGRectMake(self.expression.frame.size.width+self.expression.frame.origin.x, self.record.frame.origin.y, self.record.frame.size.width,self.record.frame.size.width);
    
    if (_tooBarType == TKIMToolBarLonelyType) {
       self.input.frame=CGRectMake(20,  self.frame.size.height*0.15, self.width-40, ToolBarHeight*0.7);
    }
//#warning 暂时全部设为需要语音
//    self.isNeedVoice = YES;
    if (!self.isNeedVoice) {
        
        self.input.frame = CGRectMake(15,  self.record.top+4, self.expression.frame.origin.x - 20, ToolBarHeight*0.7);
    }
    
    self.record.hidden = !self.isNeedVoice;
}

/**
 *  @Author lpm, 15-07-27 14:07:44
 *
 *  @brief  监听事件
 */
-(void)addNotification
{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardShow:) name:UIKeyboardWillShowNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardHide:) name:UIKeyboardWillHideNotification object:nil];
}


/**
 *  @Author lpm, 15-07-27 14:07:54
 *
 *  @brief  键盘显示
 *
 *  @param note
 */
-(void)keyboardShow:(NSNotification *)note
{
    CGRect keyBoardRect=[note.userInfo[UIKeyboardFrameEndUserInfoKey] CGRectValue];
    CGFloat deltaY= keyBoardRect.size.height;
    CGFloat duration = [note.userInfo[UIKeyboardAnimationDurationUserInfoKey] floatValue];
    if(_delegate &&[_delegate respondsToSelector:@selector(keyBoardShow:duration:)])
    {
        [_delegate keyBoardShow:deltaY duration:duration];
    }
    [UIView animateWithDuration:duration animations:^
     {
         //改变当前视图的位置
         self.transform = CGAffineTransformMakeTranslation(0, -deltaY);
     } completion:^(BOOL finished) {
         
     }];
}


/**
 *  @Author lpm, 15-07-27 14:07:06
 *
 *  @brief  键盘隐藏
 *
 *  @param note
 */
-(void)keyboardHide:(NSNotification *)note
{
    //如果当前没有要显示的视图，则是真正的隐藏
    if (!_activeBottomView)
    {
        [CATransaction begin];
        [CATransaction setDisableActions:YES];

        CGRect keyBoardRect=[note.userInfo[UIKeyboardFrameEndUserInfoKey] CGRectValue];
        CGFloat deltaY= keyBoardRect.size.height;

        CGFloat duration = [note.userInfo[UIKeyboardAnimationDurationUserInfoKey] floatValue];
        self.transform = CGAffineTransformIdentity;

            if(_delegate &&[_delegate respondsToSelector:@selector(keyBoardHide:duration:)])
            {
                [_delegate keyBoardHide:deltaY duration:duration];
            }

        [CATransaction commit];
    }
}


#pragma mark 方法



/**
 *  @Author lpm, 15-08-03 16:08:29
 *
 *  @brief  切换表情键盘
 */
-(void)doChange:(UIButton *)button
{
    if (_activeBottomView||_activeBottomView.superview)
    {
        [_activeBottomView removeFromSuperview];
    }

    switch (_keyBoardType)
    {
        case System://系统键盘
        {
            [button setImage:TKIMGetImage(@"im_icon_keyboard_nor") forState:UIControlStateNormal];
            if (button == self.expression)
            {
                _activeBottomView = self.emotionView;
                _keyBoardType = Emotion;
            }
            else if(button == self.tool)
            {
                _activeBottomView = self.toolView;
                _keyBoardType = More;
                
            }
            else if(button == self.record)
            {
                _activeBottomView = self.recordView;
                _keyBoardType = Voice;
            }

            _activeButton = button;
            [self addSubview:_activeBottomView];
            
            if(_delegate &&[_delegate respondsToSelector:@selector(keyBoardShow:duration:)])
            {
                [_delegate keyBoardShow:_activeBottomView.frame.size.height duration:keyBoardDuration];
            }
            if ([self.input isFirstResponder])
            {
                [self.input resignFirstResponder];
            }
        }
            break;
        default://非系统键盘
        {
            [self changeActiveButtonState];
            if (_activeButton == button)
            {
                _keyBoardType = System;
                [self.input becomeFirstResponder];
                _activeBottomView = nil;
                _activeButton = nil;
            }
            else
            {
                [button setImage:TKIMGetImage(@"im_icon_keyboard_nor") forState:UIControlStateNormal];
                if (button == self.expression)
                {
                    _activeBottomView = self.emotionView;
                    _keyBoardType = Emotion;
                }
                else if(button == self.tool)
                {
                    _activeBottomView = self.toolView;
                    _keyBoardType = More;
                }
                else if(button == self.record)
                {
                    _activeBottomView = self.recordView;
                    _keyBoardType = Voice;
                }

                [self addSubview:_activeBottomView];

                if(_delegate &&[_delegate respondsToSelector:@selector(keyBoardShow:duration:)])
                {
                    [_delegate keyBoardShow:_activeBottomView.frame.size.height duration:keyBoardDuration];
                }

            }
            _activeButton = button;
        }
            break;
    }
    
    if (_activeBottomView)
    {
        [UIView animateWithDuration:keyBoardDuration animations:^
        {
            //改变当前视图的大小
            self.frame = CGRectMake(self.frame.origin.x, self.frame.origin.y, self.frame.size.width, _activeBottomView.frame.size.height+ToolBarHeight);

            //改变当前视图的位置
            self.transform = CGAffineTransformMakeTranslation(0,-_activeBottomView.frame.size.height);

        } completion:^(BOOL finished)
        {
        }];
    }
}


/**
 *  @Author lpm, 15-08-03 17:08:43
 *
 *  @brief  改变当前活跃按钮的状态
 *
 *  @param dic
 */
-(void)changeActiveButtonState
{
    NSString *imgName = @"";
    switch (_keyBoardType)
    {
        case Emotion:
            imgName = @"im_icon_face_normal";
            break;
        case More:
            imgName = @"im_but_tool";
            break;
        case Voice:
            imgName = @"im_icon_voice";
            break;

        default:
            break;
    }
    [_activeButton setImage:TKIMGetImage(imgName) forState:UIControlStateNormal];
}


/**
 *  @Author lpm, 15-10-27 15:10:24
 *
 *  @brief  事件路由
 *
 *  @param eventName
 *  @param userInfo
 */
-(void)routerEventWithName:(NSString *)eventName userInfo:(NSObject *)userInfo
{
    if ([eventName isEqualToString:TKIMEmotionClickEvent])
    {
        [self emotionOnClick:(NSMutableDictionary *)userInfo];
    }
    else if([eventName isEqualToString:TKIMEmotionDeleteEvent])
    {   //不考虑光标的位置，直接删除最后一个字符
        NSMutableAttributedString * attrStr = [[NSMutableAttributedString alloc] initWithAttributedString:self.input.attributedText];
        NSUInteger length = attrStr.string.length;
        if (attrStr.string.length) {
            [attrStr replaceCharactersInRange:NSMakeRange(length-1, 1) withString:@""];
        }
        self.input.attributedText = attrStr;
    }
    else if([eventName isEqualToString:TKIMEmotionSendEvent])
    {
        [self doSend];
    }
    else if([eventName isEqualToString:TKIMSwitchTooBarEvent])
    {
        [self switchToolBar];
    }
    else
    {
        [super routerEventWithName:eventName userInfo:userInfo];
    }
}


/**
 *  @Author lpm, 15-07-27 16:07:22
 *
 *  @brief  点击发送按钮发送消息
 *
 *  @param message
 */
-(void)doSend
{
    
    
    
    if (self.input.attributedText.length==0) {
        return;
    }
    
    NSString *str = [self filterMessage:self.input.attributedText];
    
    if(_delegate &&[_delegate respondsToSelector:@selector(sendTxt:)])
    {
        [_delegate sendTxt:str];
        self.input.text = @"";
        self.input.attributedText = nil;
    }
}

-(void)doReply:(UIButton*)btn
{
    
    if(_delegate &&[_delegate respondsToSelector:@selector(replyBtnClick:)])
    {
        [_delegate replyBtnClick:btn];
    }
}


/**
 *  @Author lpm, 15-08-03 17:08:43
 *
 *  @brief  发送表情
 *
 *  @param dic
 */
-(void)emotionOnClick:(NSMutableDictionary *)dic
{
    NSString *name = dic[@"value"];
    
    NSTextAttachment * attach = [[NSTextAttachment alloc] init];
    attach.image = TKIMGetImage(name);
    [attach.image  setAccessibilityIdentifier:name];
    CGFloat attchWH = self.input.font.lineHeight;
    attach.bounds = CGRectMake(0, -4, attchWH, attchWH);
    NSAttributedString * emotion = [NSAttributedString attributedStringWithAttachment:attach];
    
    NSMutableAttributedString *attributedText = [[NSMutableAttributedString alloc] init];
    // 拼接之前的文字（图片和普通文字）
    [attributedText appendAttributedString:self.input.attributedText];
    [attributedText replaceCharactersInRange:self.input.selectedRange withAttributedString:emotion];
    
    NSUInteger loc = self.input.selectedRange.location;
    [attributedText addAttribute:NSFontAttributeName value:self.input.font range:NSMakeRange(0, attributedText.length)];
    self.input.attributedText = attributedText;
    //将光标移动到插入的表情之情
    self.input.selectedRange = NSMakeRange(loc + 1, 0);
    [self.input scrollRangeToVisible:NSMakeRange(self.input.attributedText.length, 1)];
}


#pragma mark 属性

-(UIView *)tooBar
{
    if (!_tooBar)
    {
        _tooBar = [[UIView alloc] initWithFrame:CGRectMake(0, 0, self.width, ToolBarHeight)];
        
        [_tooBar addSubview:self.switchBar];
        
        if (_tooBarType == TKIMToolBarOfiicalType)
        {
            UILabel *line = [[UILabel alloc] initWithFrame:CGRectMake(self.switchBar.right, 0, lineWidth, self.height-6)];
            line.backgroundColor = [TKIMColorHelper stringToColor:@"#cccccc"];
            [_tooBar addSubview:line];
        }
        
        [_tooBar addSubview:self.record];
        [_tooBar addSubview:self.input];
        [_tooBar addSubview:self.expression];
        [_tooBar addSubview:self.tool];
        

    }
    self.input.frame=CGRectMake(self.isNeedVoice ? self.record.frame.size.width+self.record.frame.origin.x+2 : 10,  self.frame.size.height*0.15, (self.frame.size.width-3*ToolBarHeight +14-self.switchBar.width), ToolBarHeight*0.7);
    return _tooBar;
}

-(UIView *)inputBar
{
    if (!_inputBar)
    {
        _inputBar = [[UIView alloc] initWithFrame:CGRectMake(0, 0, self.width, ToolBarHeight)];
        
        if (_tooBarType == TKIMToolBarOfiicalType)
        {
            UILabel *line = [[UILabel alloc] initWithFrame:CGRectMake(self.switchBar.right, 0, lineWidth, self.height-6)];
            line.backgroundColor = [TKIMColorHelper stringToColor:@"#cccccc"];
            [_tooBar addSubview:line];
        }
        

        [_inputBar addSubview:self.input];


    }
    self.input.frame=CGRectMake(20,  self.frame.size.height*0.15, self.width-40, ToolBarHeight*0.7);
    return _inputBar;
}


-(TKIMMenuBar *)menuBar
{
    if (!_menuBar)
    {
        _menuBar = [[TKIMMenuBar alloc] initWithFrame:CGRectMake(0,0, self.width, ToolBarHeight)];
        _menuBar.backgroundColor = [UIColor clearColor];
    }
    return _menuBar;
}



-(UIButton *)switchBar
{
    if (!_switchBar)
    {
        if (_tooBarType == TKIMToolBarNormalType)
        {
            _switchBar = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 0, 0)];
        }
        else
        {
            _switchBar = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 50, self.height)];
        }
        [_switchBar setImage:TKIMGetImage(@"im_but_keyboardDown") forState:UIControlStateNormal];
        [_switchBar addTarget:self action:@selector(switchToolBar) forControlEvents:UIControlEventTouchUpInside];
    }
    return _switchBar;
}



-(UIButton *)record
{
    if (!_record)
    {
        CGFloat x =self.switchBar.right==0?3:self.switchBar.right;
        _record = [[UIButton alloc] initWithFrame:CGRectMake(x, 4, ToolBarHeight-8,ToolBarHeight-8)];
        [_record setImage:TKIMGetImage(@"im_icon_voice") forState:UIControlStateNormal];
        _record.imageEdgeInsets = UIEdgeInsetsMake(3, 3, 3, 3);
        [_record addTarget:self action:@selector(doChange:) forControlEvents:UIControlEventTouchUpInside];
    }
    return _record;
}


// 输入框
-(UITextView *)input
{
    if (!_input)
    {
        _input = [[TKIMToolBarTextView alloc] init];
        _input.backgroundColor = [UIColor whiteColor];
        _input.font = [UIFont systemFontOfSize:15.0f];
        _input.layer.borderColor = [TKIMColorHelper stringToColor:@"#cccccc"].CGColor;
        CGFloat scale = [[UIScreen mainScreen] scale];
        CGFloat width = scale > 0.0 ? 1.0 / scale : 1.0;
        _input.layer.borderWidth = width;
        _input.layer.cornerRadius = 5.0f;
        _input.delegate = self;
        _input.returnKeyType = UIReturnKeySend;
        [_input.layer setMasksToBounds:YES];
    }
    return _input;
}

//-(UITextView *)input2
//{
//    if (!_input2)
//    {
//        _input2 = [[UITextView alloc] initWithFrame:CGRectMake(20,  self.frame.size.height*0.15, self.frame.size.width-40, ToolBarHeight*0.7)];
//        _input2.backgroundColor = [UIColor whiteColor];
//        _input2.font = [UIFont systemFontOfSize:15.0f];
//        _input2.layer.borderColor = [TKIMColorHelper stringToColor:@"#cccccc"].CGColor;
//        CGFloat scale = [[UIScreen mainScreen] scale];
//        CGFloat width = scale > 0.0 ? 1.0 / scale : 1.0;
//        _input2.layer.borderWidth = width;
//        _input2.layer.cornerRadius = 5.0f;
//        _input2.delegate = self;
//        _input2.returnKeyType = UIReturnKeySend;
//        [_input2.layer setMasksToBounds:YES];
//    }
//    return _input2;
//}


// 表情button
-(UIButton *)expression
{
    if (!_expression)
    {
        _expression = [[UIButton alloc] initWithFrame:CGRectMake(self.input.frame.size.width+self.input.frame.origin.x+2, self.record.frame.origin.y, self.record.frame.size.width,self.record.frame.size.width)];
        [_expression setImage:TKIMGetImage(@"im_icon_face_normal") forState:UIControlStateNormal];
        _expression.imageEdgeInsets = UIEdgeInsetsMake(3, 3, 3, 3);
        [_expression addTarget:self action:@selector(doChange:) forControlEvents:UIControlEventTouchUpInside];
    }
    return _expression;
}


// 加号
-(UIButton *)tool
{
    if (!_tool)
    {
        _tool = [[UIButton alloc] initWithFrame:CGRectMake(self.expression.frame.size.width+self.expression.frame.origin.x, self.record.frame.origin.y, self.record.frame.size.width,self.record.frame.size.width)];
        [_tool setImage:TKIMGetImage(@"im_but_tool") forState:UIControlStateNormal];
        _tool.imageEdgeInsets = UIEdgeInsetsMake(3, 3, 3, 3);
        [_tool addTarget:self action:@selector(doChange:) forControlEvents:UIControlEventTouchUpInside];
    }
    return _tool;
}


-(UIButton *)send
{
    if (!_send)
    {
        _send = [[UIButton alloc] initWithFrame:CGRectMake(self.input.frame.size.width+self.input.frame.origin.x+5, self.input.frame.origin.y, self.frame.size.height, _input.frame.size.height)];
        _send.backgroundColor = [TKIMColorHelper stringToColor:@"#E9E9E9"];
        _send.layer.borderColor = [TKIMColorHelper stringToColor:@"#cccccc"].CGColor;
        _send.layer.borderWidth = 1.0f;
        _send.titleLabel.font = [UIFont systemFontOfSize:13.0f];
        [_send setTitle:@"发送" forState:UIControlStateNormal];
        [_send setTitleColor: [TKIMColorHelper stringToColor:@"#9A9A9A"] forState:UIControlStateNormal];
        [_send setTitleColor: [TKIMColorHelper stringToColor:@"#cccccc"] forState:UIControlStateHighlighted];
        [_send.layer setMasksToBounds:YES];
        _send.layer.cornerRadius = 5.0f;
        [_send addTarget:self action:@selector(doSend) forControlEvents:UIControlEventTouchUpInside];
    }
    return _send;
}

-(UIButton *)reCall
{
    if (!_reCall)
    {
        _reCall = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, self.frame.size.width, self.frame.size.height)];
        _reCall.titleLabel.font = [UIFont systemFontOfSize:16.0f];
        [_reCall setTitle:@"回呼" forState:UIControlStateNormal];
        [_reCall setTitleColor: [TKIMColorHelper stringToColor:@"#333333"] forState:UIControlStateNormal];
        [_reCall setTitleColor: [TKIMColorHelper stringToColor:@"#333333"] forState:UIControlStateHighlighted];
        UIImage* image=[UIImage imageNamed:@"repla_call"];
        [_reCall setImage:image forState:UIControlStateNormal];
        CGFloat y=(self.frame.size.height-17)/2;
        _reCall.imageEdgeInsets = UIEdgeInsetsMake(y, 0, y,0);
        _reCall.titleEdgeInsets = UIEdgeInsetsMake(0, image.size.width, 0, 0);
        _reCall.contentHorizontalAlignment = UIControlContentHorizontalAlignmentCenter;
        [_reCall addTarget:self action:@selector(doReply:) forControlEvents:UIControlEventTouchUpInside];
    }
    return _reCall;
}


-(TKIMEmotionView *)emotionView
{
    if (!_emotionView)
    {
        _emotionView = [[TKIMEmotionView alloc] initWithFrame:CGRectMake(0, ToolBarHeight, self.frame.size.width, self.frame.size.width*3/7+40) ];
        _emotionView.backgroundColor = [UIColor whiteColor];
        _emotionView.backgroundColor = [TKIMColorHelper stringToColor:@"#EFEFF4"];
    }
    return _emotionView;
}


-(TKIMToolView *)toolView
{
    if (!_toolView)
    {
        if (!_isNeedPhoto) {
            _toolView = [[TKIMToolView alloc] initNoNeedPhotoWithFrame:CGRectMake(0, ToolBarHeight, self.frame.size.width, self.frame.size.width*2/4+30)];
        }else{
            
            if (_isNeedQuick) {
                _toolView = [[TKIMToolView alloc] initWithFrame:CGRectMake(0, ToolBarHeight, self.frame.size.width, self.frame.size.width*2/4+30) ];
            }else{
                _toolView = [[TKIMToolView alloc] initNoNeedQuickWithFrame:CGRectMake(0, ToolBarHeight, self.frame.size.width, self.frame.size.width*2/4+30)];
            }
        }
        _toolView.backgroundColor = [UIColor whiteColor];
        _toolView.backgroundColor = [TKIMColorHelper stringToColor:@"#EFEFF4"];
        _toolView.isShowPageCount = NO;
        
    }
    return _toolView;
}


-(TKIMRecordView *)recordView
{
    if (!_recordView)
    {
        _recordView = [[TKIMRecordView alloc] initWithFrame:CGRectMake(0, ToolBarHeight, self.frame.size.width, self.frame.size.width*2/4+30) ];
        _recordView.backgroundColor = [UIColor whiteColor];
        _recordView.backgroundColor = [TKIMColorHelper stringToColor:@"#EFEFF4"];
    }
    return _recordView;
}

#pragma mark - setter
-(void)setMenusArray:(NSArray *)menusArray
{
    _menusArray = menusArray;
    self.menuBar.itemList = menusArray;
}

#pragma mark 输入框代理

/**
 *  @author zhengrs, 16-01-05 13:01:34
 *
 *  @brief textView的键盘return键点击时
 *
 *  @param textView
 *  @param range
 *  @param text
 *
 *  @return
 */
-(BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text
{
//    NSRange effectiveRange = {0,0};
//    TKIMTextBinding *binding;
//    if(range.location > 0 && text.length == 0){
//        binding = [textView.attributedText attribute:TKIMTextBindingAttributeName atIndex:range.location longestEffectiveRange:&effectiveRange inRange:NSMakeRange(0, textView.attributedText.length)];
//    }
    
    if ([text isEqualToString:@"\n"]){
        [self doSend];
        return NO;
    }else if ([text isEqualToString:@"@"]){
//        [self doRemind];
        return YES;
    }
//    else if(binding&& binding.deleteConfirm){
//        NSMutableAttributedString *attributedText = [[NSMutableAttributedString alloc] initWithAttributedString:self.input.attributedText];
//        [attributedText replaceCharactersInRange:effectiveRange withString:@""];
//        NSUInteger loc = effectiveRange.location;
//        self.input.attributedText = attributedText;
//        self.input.selectedRange = NSMakeRange(loc, 0);
//        return NO;
//    }
    return YES;
}


/**
 *  @Author lpm, 16-05-23 16:05:17
 *
 *  @brief  光标改变
 *
 *  @param textView
 */
- (void)textViewDidChangeSelection:(UITextView *)textView
{
    NSRange range = textView.selectedRange;
    NSRange effectiveRange = {0,0};
    TKIMTextBinding *binding;
    NSString *text = textView.text;
    if(range.location > 0&& text.length > 0){
        binding = [textView.attributedText attribute:TKIMTextBindingAttributeName atIndex:range.location-1 longestEffectiveRange:&effectiveRange inRange:NSMakeRange(0, textView.attributedText.length)];
    }
    
    if(binding){
        if (range.location > effectiveRange.location && range.location < effectiveRange.length+effectiveRange.location)
        {
            if (range.location > effectiveRange.length/2)
            {
                self.input.selectedRange = NSMakeRange(effectiveRange.length+effectiveRange.location, 0);
            }
            else
            {
                self.input.selectedRange = NSMakeRange(effectiveRange.location, 0);
            }
        }
    }
}





-(BOOL)textViewShouldBeginEditing:(UITextView *)textView
{
    if (_keyBoardType != System)
    {
        if (_activeBottomView) {
            if (_activeBottomView.superview)
            {
                [_activeBottomView removeFromSuperview];
            }
            _activeBottomView = nil;
        }
        [self changeActiveButtonState];
        _activeButton = nil;
        _keyBoardType = System;
    }
    
    return YES;
}


/**
 *  @Author lpm, 15-07-29 16:07:38
 *
 *  @brief  收起键盘
 */
-(void)resignInputFirstResponder
{
    if ([_input isFirstResponder])
    {
        [_input resignFirstResponder];
    }
    
    if (_activeBottomView)
    {
        if(_delegate &&[_delegate respondsToSelector:@selector(keyBoardHide:duration:)])
        {
            [_delegate keyBoardHide:_activeBottomView.frame.size.height duration:keyBoardDuration];
        }
        [self changeActiveButtonState];
        _activeButton = nil;
        _keyBoardType = System;
        
        [UIView animateWithDuration:keyBoardDuration animations:^
        {
            self.transform = CGAffineTransformIdentity;
        } completion:^(BOOL finished) {
            if (_activeBottomView.superview)
            {
                [_activeBottomView removeFromSuperview];
            }
            _activeBottomView =nil;

        }];
        
    }
}

/**
 *  @author zhengrs, 16-01-06 14:01:13
 *
 *  @brief 过滤消息(将输入框中的表情附件转化为[@emoji_%@]这种格式，发送给服务器)
 *
 *  @param text 输入框的属性字符串
 *
 *  @return 普通字符串
 */
-(NSString *)filterMessage:(NSAttributedString *)text
{
    NSAttributedString * att = self.input.attributedText;
    
    NSMutableAttributedString * resutlAtt = [[NSMutableAttributedString alloc]initWithAttributedString:att];
    
    //枚举出所有的附件字符串
    [att enumerateAttributesInRange:NSMakeRange(0, att.length) options:NSAttributedStringEnumerationReverse usingBlock:^(NSDictionary *attrs, NSRange range, BOOL *stop) {
        //key-NSAttachment
        //NSTextAttachment value类型
        NSTextAttachment * textAtt = attrs[@"NSAttachment"];//从字典中取得那一个图片
        if (textAtt)
        {
            UIImage * image = textAtt.image;
            NSString * name = [image accessibilityIdentifier];
            NSString *replace = [NSString stringWithFormat:@"[@emoji_%@]",name];
            [resutlAtt replaceCharactersInRange:range withString:replace];
        }
    }];
    
    return resutlAtt.string;
}


/**
 *  @Author lpm, 15-11-20 15:11:15
 *
 *  @brief  切换工具栏
 */
-(void)switchToolBar
{
    if (self.menuBar.superview)
    {
        //通知子菜单隐藏
        [self.menuBar hidePopView];
        
        [self.menuBar removeFromSuperview];
        [self addSubview:self.tooBar];
    }
    else if (self.tooBar.superview)
    {
        [self resignInputFirstResponder];
        [self.tooBar removeFromSuperview];
        [self addSubview:self.menuBar];
    }
}


-(void)dealloc
{
    [self.toolView removeCss];
    [self.recordView removeCss];
    [self.emotionView removeCss];
    self.toolView = nil;
    self.recordView = nil;
    self.emotionView = nil;
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

-(void)typeAheadText:(NSString*)text{
    _input.text=text;
    [_input becomeFirstResponder];
}

@end
